package com.cjm.one.common.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.cjm.one.common.utils.AuthSysUserContextHolder;
import com.cjm.one.common.utils.RequestPathContextHolder;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
@Slf4j
public class CustomTenantHandler implements TenantLineHandler {
    private static final AntPathMatcher pathMatcher = new AntPathMatcher();
    @Override
    public Expression getTenantId() {
        String path = RequestPathContextHolder.getPath();
        boolean isAppPath = pathMatcher.match("/app/**", path);
        boolean isAdminPath = pathMatcher.match("/admin/**", path);
        if (isAdminPath) {
            // 假设有一个租户上下文，能够从中获取当前用户的租户
            Long tenantId = AuthSysUserContextHolder.getAuthContextSysUser().getId();
            log.info("当前租户ID为：{}", tenantId);
            // 返回租户ID的表达式，LongValue 是 JSQLParser 中表示 bigint 类型的 class
            return new LongValue(tenantId);
        }
        return null;
    }

    @Override
    public String getTenantIdColumn() {
        return "tenant_id";
    }

    @Override
    public boolean ignoreTable(String tableName) {
        // 根据需要返回是否忽略该表
        Set<String> ignoreTableSet = new HashSet<>(List.of("sys_config",
                "sys_dict_data","sys_dict_type",
                "sys_resource","sys_role_res",
                "sys_role_dept","sys_user_post","sys_user_role",
                "order_item","order_statistics","order_info",
                "goods_brand","goods_attr","goods_category","goods_cart","goods_category_brand","goods_comment",
                "goods_details","goods_info","goods_regional_inventory","goods_sku","goods_spec",
                "goods_total_inventory","goods_unit","goods_comment_tag","goods_comment_tag_list","custom_grade","custom_sign_in",
                "custom_address","customer_balance_record","goods_browse_history","goods_collect","customer_info","customer_login_log","region",
                "undo_log",
                "coupon_info","coupon_range","customer_coupon"));

        return ignoreTableSet.contains(tableName);
    }
}
